Learning PHP 7 by Antonio Lopez

Learning PHP 7 by Antonio Lopez

Author:Antonio Lopez [Lopez, Antonio]
Language: eng
Format: epub, pdf
Publisher: Packt Publishing
Published: 2016-03-28T22:00:00+00:00


This last method expects that both the path of the request and the URL of the route follow the same pattern. With the explode method, we get two arrays that should match each of their entries. We iterate them, and for each entry in the route array that looks like a parameter, we fetch its value in the URL. For example, if we had the route /books/:id/borrow and the path /books/12/borrow, the result of this method would be the array ['id' => 12].

Executing the controller

We end this section by implementing the method that executes the controller in charge of a given route. We already have the name of the class, the method, and the arguments that the method needs, so we could make use of the call_user_func_array native function that, given an object, a method name, and the arguments for the method, invokes the method of the object passing the arguments. We have to make use of it as the number of arguments is not fixed, and we cannot perform a normal invocation.

But we are still missing a behavior introduced when creating our routes.json file. There are some routes that force the user to be logged in, which, in our case, means that the user has a cookie with the user ID. Given a route that enforces authorization, we will check whether our request contains the cookie, in which case we will set it to the controller class through setCustomerId. If the user does not have a cookie, instead of executing the controller for the current route, we will execute the showLogin method of the CustomerController class, which will render the template for the login form. Let's see how everything would look on adding the last method of our Router class:

private function executeController( string $route, string $path, array $info, Request $request ): string { $controllerName = '\Bookstore\Controllers\\' . $info['controller'] . 'Controller'; $controller = new $controllerName($request); if (isset($info['login']) && $info['login']) { if ($request->getCookies()->has('user')) { $customerId = $request->getCookies()->get('user'); $controller->setCustomerId($customerId); } else { $errorController = new CustomerController($request); return $errorController->login(); } } $params = $this->extractParams($route, $path); return call_user_func_array( [$controller, $info['method']], $params ); }



Download



Copyright Disclaimer:
This site does not store any files on its server. We only index and link to content provided by other sites. Please contact the content providers to delete copyright contents if any and email us, we'll remove relevant links or contents immediately.